package org.example;

import org.beetl.core.Context;
import org.beetl.core.GroupTemplate;
import org.beetl.core.engine.DefaultTemplateEngine;
import org.beetl.core.engine.GrammarCreator;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.statement.*;

import java.io.IOException;

/**
 * @ClassName: MyPlaceHolderEngine
 * @Author: 孙磊
 * @Date: 2024/7/24 23:56
 * @Since: JDK1.8
 * @Version: 1.0
 */
public class MyPlaceHolderEngine extends DefaultTemplateEngine {

    protected GrammarCreator getGrammarCreator(GroupTemplate groupTemplate) {
        GrammarCreator result = new MyPlaceHolderGrammarCreator();
        return result;
    }

    static class MyPlaceHolderGrammarCreator extends  GrammarCreator{

        @Override
        public PlaceholderST createTextOutputSt(Expression exp, FormatExpression format) {

            if(exp instanceof VarRef){
                // #{a.c} 最简单的变量输出
                return new TextShow(exp, format, null);
            }else{
                return  new PlaceholderST(exp,format,null);
            }

        }
    }

    public static class TextShow extends PlaceholderST {

        public TextShow(Expression exp, FormatExpression format, GrammarToken token) {
            super(exp, format, token);
        }

        @Override
        public void execute(Context ctx) {
            try{
                super.execute(ctx);
            }catch (BeetlException ex){
                if(ex.detailCode.equals(BeetlException.VAR_NOT_DEFINED)){
                    showText(ctx);
                    return ;
                }
                throw ex;
            }
        }
        protected void showText(Context ctx){
            String start1 = ctx.template.gt.getConf().getPlaceholderStart();
            String end1 = ctx.template.gt.getConf().getPlaceholderEnd();
            try{
                ctx.byteWriter.writeString(start1);
                ctx.byteWriter.writeString(getText(expression));
                ctx.byteWriter.writeString(end1);
            }catch (IOException ioe){
                //do nothing
            }

        }

        protected  String getText(Expression expression){
            if(expression instanceof VarRef){
                VarRef ref = (VarRef)expression;
                return ref.token.text;
            }

            throw new UnsupportedOperationException("不支持的表达式");
        }
    }

}
